﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace WXWorkSvc.Common.Services;

public class JWTService
{
    private readonly IConfiguration _configuration;

    public JWTService(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public string CreateToken(params Claim[] claims)
    {
        //var typeClaims = typeof(ClaimTypes);
        
        // 1. 定义需要使用到的Claims
        //var claims = new List<Claim>();
        //for (int i = 0; i < kvs.Length / 2; i++)
        //{
        //    var value = typeClaims.GetField("Name")?.GetValue(null);

        //    if (value == null)
        //        claims.Add(new Claim(kvs[i * 2], kvs[i * 2 + 1]));
        //    else
        //        claims.Add(new Claim(value.ToString()!, kvs[i * 2 + 1]));
        //}
        // 2. 从 appsettings.json 中读取SecretKey
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]!));

        // 3. 选择加密算法
        var algorithm = SecurityAlgorithms.HmacSha256;

        // 4. 生成Credentials
        var signingCredentials = new SigningCredentials(secretKey, algorithm);

        // 5. 根据以上，生成token
        var jwtSecurityToken = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims,
            DateTime.Now,
            DateTime.Now.AddDays(1),
            signingCredentials
        );

        // 6. 将token变为string
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }
}

